package queryip

import (
	"io"
	"net/http"
	"strings"

	"gitee.com/smewl13/beehive/pkg/lhttp"
	"github.com/PuerkitoBio/goquery"
	"github.com/spf13/viper"
	"go.uber.org/zap"
)

func NewQueryIP(logger *zap.Logger, conf *viper.Viper) *QueryIP {
	method := strings.TrimSpace(conf.GetString("website.web_type"))
	rawUrl := strings.TrimSpace(conf.GetString("website.url"))
	switch method {
	case "text", "html":
	case "":
		method = "text"
	default:
		logger.Fatal(
			"[公网IP查询]不支持的网页类型,目前支持html、text", zap.String("type", method),
		)
	}

	if rawUrl == "" {
		rawUrl = "https://ip.3322.net/"
	}

	return &QueryIP{
		webType: method,
		logger:  logger,
		client:  lhttp.NewClient(logger, rawUrl),
	}
}

type QueryIP struct {
	Status  bool
	IP      string
	webType string
	client  *lhttp.Client
	logger  *zap.Logger
}

func (q *QueryIP) Handle() {
	resp := q.client.Request("GET", nil, nil)
	if resp == nil {
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		q.logger.Error("[公网IP查询]请求失败", zap.Int("status_code", resp.StatusCode))
		return
	}

	if q.webType != "html" {
		b, err := io.ReadAll(resp.Body)
		if err != nil {
			q.logger.Error("[公网IP查询]读取body失败", zap.Error(err))
			return
		}

		q.IP = strings.TrimSpace(string(b))
		q.Status = true
		return
	}

	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		q.logger.Error("[公网IP查询]解析body失败", zap.Error(err))
		return
	}

	doc.Find("div").Each(func(i int, s *goquery.Selection) {
		q.IP = strings.TrimSpace(s.Text())
		q.Status = true
	})
}
